package com.liuc.practice.server.pojo;

import com.liuc.practice.server.util.InputStreamUtil;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author Liu Chang
 * @Date 2021/7/22 1:40 下午
 */
public class Request {

    private String method;

    private String url;

    private InputStream inputStream;

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public Request() {
    }

    public Request(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;
        String inputInfoStr = getInputInfo(this.inputStream);
        parseInputInfo(inputInfoStr);
    }

    private String getInputInfo(InputStream inputStream) throws IOException {
        // 由于数据传输可能存在延迟，即请求过来了，但数据没到，因此做以下处理
        int count = InputStreamUtil.getInputStreamBytesCount(inputStream);

        byte[] bytes = new byte[count];
        // 读取数据流字节，存储到缓冲区数组
        inputStream.read(bytes);
        return new String(bytes);
    }

    private void parseInputInfo(String inputInfoStr) {
        String firstLine = inputInfoStr.split("\\n")[0];
        String[] methodAndUrl = firstLine.split(" ");
        this.method = methodAndUrl[0];
        this.url = methodAndUrl[1];

        System.out.println("method: " + method);
        System.out.println("url: " + url);
    }
}
